package com.xhwl.centiotdata.service.parkingguidance;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.integration.parkingguidance.ParkingGuidanceFactory;
import com.xhwl.centiotdata.integration.parkingguidance.ParkingGuidanceIntegrationConfig;
import com.xhwl.centiotdata.integration.parkingguidance.ParkingGuidanceSystemHandler;
import com.xhwl.centiotdata.integrator.parkingguidance.ParkingGuidanceRequestsDTO;
import com.xhwl.centiotdata.integrator.parkingguidance.ParkingGuidanceResponseDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.service.cent.ISpaceCentService;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultBuilder;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.query.cent.sdata.SpaceQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Falcon.cao @Copyright (C), 2022, 兴海物联
 * Date: 2022/10/5 10:12
 * Description: 包信息
 */
@Service
public class ParkingGuidanceServiceImpl implements ParkingGuidanceService {

    @Autowired
    private ParkingGuidanceFactory parkingGuidanceFactory;

    @Autowired
    private IProjectCentService projectCentService;

    @Autowired
    private ISpaceCentService spaceCentService;

    @Autowired
    private IDeviceCentService iDeviceCentService;

    @Override
    public ResultJson<List<ParkingGuidanceResponseDTO>> onListingParkingArea(ParkingGuidanceRequestsDTO dto) {
        List<ParkingGuidanceResponseDTO> targets = new LinkedList<>();
        List<ParkingGuidanceIntegrationConfig> configs = parkingGuidanceFactory.onFindingIntegrationConfigs(dto.getProjectId());
        for (ParkingGuidanceIntegrationConfig config : configs) {
            ParkingGuidanceSystemHandler handlers = parkingGuidanceFactory.onFindingIntegrationHandler(config.getProductName());
            targets.addAll(handlers.onListingParkingArea(config, dto));
        }
        return ResultBuilder.success(targets);
    }

    @Override
    public ResultJson<List<ParkingGuidanceResponseDTO>> onListingSpaceStatus(ParkingGuidanceRequestsDTO dto) {
        List<ParkingGuidanceResponseDTO> targets = new LinkedList<>();
        List<ParkingGuidanceIntegrationConfig> configs = parkingGuidanceFactory.onFindingIntegrationConfigs(dto.getProjectId());
        for (ParkingGuidanceIntegrationConfig config : configs) {
            ParkingGuidanceSystemHandler handlers = parkingGuidanceFactory.onFindingIntegrationHandler(config.getProductName());
            targets.addAll(handlers.onListingSpaceStatus(config, dto));
        }
        return ResultBuilder.success(targets);
    }

    @Override
    public ResultJson<ParkingGuidanceResponseDTO> onGettingSpaceStatus(ParkingGuidanceRequestsDTO dto) {
        List<ParkingGuidanceIntegrationConfig> configs = parkingGuidanceFactory.onFindingIntegrationConfigs(dto.getProjectId());
        for (ParkingGuidanceIntegrationConfig config : configs) {
            ParkingGuidanceSystemHandler handlers = parkingGuidanceFactory.onFindingIntegrationHandler(config.getProductName());
            ParkingGuidanceResponseDTO response = handlers.onGettingSpaceStatus(config, dto);
            if (response != null) {
                return ResultBuilder.success(response);
            }
        }
        return ResultBuilder.failure("未查询到该车位数据");
    }

    @Override
    public ResultJson onGettingSpaceStatusByPosition(ParkingGuidanceRequestsDTO dto) {
        if(dto.getProjectId() == null){
            throw new BusinessException("项目id信息为空，即projectId");
        }
        if(dto.getParkNo() == null){
            throw new BusinessException("车位信息为空");
        }
        List<ParkingGuidanceIntegrationConfig> configs = parkingGuidanceFactory.onFindingIntegrationConfigs(dto.getProjectId());
        Integer orgId = this.orgCodeForOrgId(dto.getParkNo(), dto.getProjectId());
        DevicePageQuery devicePageQuery = new DevicePageQuery();
        devicePageQuery.setOrganizationId(orgId);
        devicePageQuery.setCategoryIdList(Collections.singletonList(configs.get(0).getProdCategoryId()));
        devicePageQuery.setProjectId(dto.getProjectId());
        List<DeviceDTO> deviceDTOS = iDeviceCentService.listDevice(null, devicePageQuery);
        if(!deviceDTOS.isEmpty()){
            if(deviceDTOS.size() == 1){
                ParkingGuidanceRequestsDTO parkingGuidanceRequestsDTO = new ParkingGuidanceRequestsDTO();
                parkingGuidanceRequestsDTO.setProjectId(dto.getProjectId());
                parkingGuidanceRequestsDTO.setAreaId(dto.getAreaId());
                parkingGuidanceRequestsDTO.setParkNo(deviceDTOS.get(0).getName());
                return this.onGettingSpaceStatus(parkingGuidanceRequestsDTO);
            }else {
                return ResultJson.fail("该空间路址上存在多个地磁设备");
            }
        }else{
            return ResultJson.fail("设备不存在");
        }
    }

    /**
     * 通过传的组织编码，来查询组织id
     */
    private Integer orgCodeForOrgId(String orgCode, Integer projectId){
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.setProjectIds(Collections.singletonList(projectId));
        List<Organization> organizationList = projectCentService.organizationList(organizationQuery);
        //先在组织表中查询，看这个code是否存在
        Organization organization1 = organizationList.stream().filter(organization -> {
            if (StringUtils.equals(orgCode, organization.getCode())) {
                return true;
            } else {
                return false;
            }
        }).findAny().orElse(null);
        if(organization1 != null){
            return organization1.getId();
        }else{
            //执行这里，表示组织表中不存在这个code，需要到space中查询
            ResultJson resultJson = spaceCentService.list(new SpaceQuery());
            if(resultJson == null || !resultJson.getState()){
                throw new BusinessException("获取空间信息的接口异常");
            }
            JSONArray spaceArray = JSONObject.parseArray(JSONObject.toJSONString(resultJson.getResult()));
            Object spaceObject1 = spaceArray.stream().filter(object -> {
                JSONObject spaceObject = JSONObject.parseObject(object.toString());
                JSONObject codeObject = JSONObject.parseObject(spaceObject.getString("data"));
                if (StringUtils.equals(
                        String.valueOf(spaceObject.getInteger("projectId")),
                        String.valueOf(projectId)) &&
                        StringUtils.equals(
                                codeObject.getString("code"), orgCode
                        )) {
                    return true;
                } else {
                    return false;
                }
            }).findAny().orElse(null);
            if(spaceObject1 == null){
                throw new BusinessException("通过该组织编码未找到相应的组织信息");
            }
            return JSONObject.parseObject(spaceObject1.toString()).getInteger("organizationId");
        }
    }
}
